package com.dji.ux.sample.TCPClient;


import android.annotation.SuppressLint;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.dji.ux.sample.Weather.WeatherParams;
import com.dji.ux.sample.Weather.WeatherUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by shensky on 2018/1/15.
 */

public class TCPClient {
    private static TCPClient instance;
    private static final String TAG = "TaskCenter";
    //    Socket
    private Socket socket;
    //    IP地址
    private String ipAddress;
    //    端口号
    private int port;
    private Thread thread;
    //    Socket输出流
    private OutputStream outputStream;
    //    Socket输入流
    private InputStream inputStream;
    //    连接回调
    private OnServerConnectedCallbackBlock connectedCallback;
    //    断开连接回调(连接失败)
    private OnServerDisconnectedCallbackBlock disconnectedCallback;
    //    接收信息回调
    private OnReceiveCallbackBlock receivedCallback;
    //    气象站信息回调
    private OnWeatherParamListener weatherParamListener;

    //    构造函数私有化
    private TCPClient() {
        super();
    }

    //    提供一个全局的静态方法
    public static TCPClient sharedCenter() {
        if (instance == null) {
            synchronized (TCPClient.class) {
                if (instance == null) {
                    instance = new TCPClient();
                }
            }
        }
        return instance;
    }

    /**
     * 通过IP地址(域名)和端口进行连接
     *
     * @param ipAddress IP地址(域名)
     * @param port      端口
     */
    public void connect(final String ipAddress, final int port) {

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket(ipAddress, port);
//                    socket.setSoTimeout ( 2 * 1000 );//设置超时时间
                    if (isConnected()) {
                        TCPClient.sharedCenter().ipAddress = ipAddress;
                        TCPClient.sharedCenter().port = port;
                        if (connectedCallback != null) {
                            connectedCallback.callback();
                        }
                        outputStream = socket.getOutputStream();
                        inputStream = socket.getInputStream();
                        receive();
                        Log.i(TAG, "连接成功");
                    } else {
                        Log.i(TAG, "连接失败");
                        if (disconnectedCallback != null) {
                            disconnectedCallback.callback(new IOException("连接失败"));
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
//                    Log.e(TAG, "连接异常");
                    if (disconnectedCallback != null) {
                        disconnectedCallback.callback(e);
                    }
                }
            }
        });
        thread.start();
    }

    /**
     * 判断是否连接
     */
    public boolean isConnected() {
        return socket.isConnected();
    }

    /**
     * 连接
     */
    public void connect() {
        connect(ipAddress, port);
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        if (isConnected()) {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                socket.close();
                if (socket.isClosed()) {
                    if (disconnectedCallback != null) {
                        disconnectedCallback.callback(new IOException("断开连接"));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接收数据
     */

    @SuppressLint("DefaultLocale")
    public void receive() {
        while (isConnected()) {
            try {
                /*得到的是16进制数，需要进行解析*/
                byte[] bt = new byte[1024];
//                获取接收到的字节和字节数
                int length = inputStream.read(bt);
                if (bt[7] == 0x06) {  //长度，PDF20页，读法 TODO
                    String str = "";
                    int t1 = Math.abs((int) bt[11]);
                    int t2 = Math.abs((int) bt[12]);
                    int t3 = Math.abs((int) bt[13]);
                    /*和发送信息一样，如READY_PICKUP_OK，在数据中是D60.1收到的应该是0000 0001 0000 0000,
                     *经过下面的处理为0x01，对应Status的枚举类
                     */
                    StringBuilder stringBuilder1 = new StringBuilder(String.format("%08d", Long.parseLong(Integer.toBinaryString(t1))));
                    StringBuilder stringBuilder2 = new StringBuilder(String.format("%08d", Long.parseLong(Integer.toBinaryString(t2))));
                    StringBuilder stringBuilder3 = new StringBuilder(String.format("%08d", Long.parseLong(Integer.toBinaryString(t3))));
                    str += stringBuilder1.reverse().toString();
                    str += stringBuilder2.reverse().toString();
                    str += stringBuilder3.reverse().toString();
                    Log.d("PLC------", str);
                    if (receivedCallback != null) {
                        receivedCallback.callback(getStatus(getStatusIndex(str)));
                    }
                }
            } catch (IOException e) {
                Log.i(TAG, "接收失败");
            }
        }
    }

    /**
     * 发送数据
     *
     * @param data 数据
     */
    public void send(final byte[] data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (socket != null) {
                    try {
                        outputStream.write(data);
                        Log.d("SENDTOPLC____", logOnTextView(data));
                        outputStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.i(TAG, "发送失败");
                    }
                } else {
                    connect();
                }
            }
        }).start();

    }

    /**
     * 回调声明
     */
    public interface OnServerConnectedCallbackBlock {
        void callback();
    }

    public interface OnServerDisconnectedCallbackBlock {
        void callback(IOException e);
    }

    public interface OnReceiveCallbackBlock {
        void callback(ArrayList<PLCStatus> receicedMessage);
    }

    public interface OnWeatherParamListener {
        void callback(WeatherParams para);
    }

    public void setConnectedCallback(OnServerConnectedCallbackBlock connectedCallback) {
        this.connectedCallback = connectedCallback;
    }

    public void setDisconnectedCallback(OnServerDisconnectedCallbackBlock disconnectedCallback) {
        this.disconnectedCallback = disconnectedCallback;
    }

    public void setReceivedCallback(OnReceiveCallbackBlock receivedCallback) {
        this.receivedCallback = receivedCallback;
    }

    public void setWeatherParamListener(OnWeatherParamListener weatherParamListener) {
        this.weatherParamListener = weatherParamListener;
    }

    /**
     * 移除回调
     */
    private void removeCallback() {
        connectedCallback = null;
        disconnectedCallback = null;
        receivedCallback = null;
    }

    private int[] getStatusIndex(String statusString) {
        int[] statusIndexArr = new int[0];
        for (int i = 0; i < statusString.length(); i++) {
            if (statusString.charAt(i) == '1') {
                statusIndexArr = Arrays.copyOf(statusIndexArr, statusIndexArr.length + 1);
                //数组的最后一个元素，arry[arry.length-1]
                statusIndexArr[statusIndexArr.length - 1] = i;
            }
        }
        return statusIndexArr;
    }

    public ArrayList<PLCStatus> getStatus(int[] index) {
        ArrayList<PLCStatus> status = new ArrayList<>();
        for (int i : index) {
            status.add(PLCStatus.values()[i]);
        }
        Log.d("PLCR------", status.toString());
        return status;
    }

    private String logOnTextView(final byte[] plcCommand) {
        byte[] bt = plcCommand;
        String str = "";
        for (int i = 0; i < bt.length; i++) {
            str += Integer.toHexString(bt[i] & 0xFF) + " - ";
        }
        return str;
    }
}
